package com.jacen.fzxs.util;

import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * 其它的一些公共操作方法
 * @author yexuhui
 * 2012-7-26 上午10:01:47
 */
public class Utils {
	
	/**
     * 生成正常的JSON RESPONSE
     * @return 无错的json串
     */
    public static String normalJsonResp() {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", 1);
        return JSON.toJSONString(resultMap);
    }
    
    /**
     * 生成正常的JSON RESPONSE
     * @return 无错的json串
     */
    public static String normalJsonResp(String info) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", 1);
        resultMap.put("info", info);
        return JSON.toJSONString(resultMap);
    }

    /**
     * 生成错误的json响应
     * @param error 错误描述
     * @return 错误的json串
     */
    public static String errorJsonResp(String error) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", 0);
        resultMap.put("message", error);
        return JSON.toJSONString(resultMap);
    }
    
    public static String errorJsonResp(String key,String error) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("code", 0);
        resultMap.put("key", key);
        resultMap.put("message", error);
        return JSON.toJSONString(resultMap);
    }

	/**
	 * 根据字符串生成32位的MD5串
	 * @param str 字符串
	 * @return 生成后的MD5
	 * @throws Exception
	 */
	public static String md5(String str) {
		char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte[] bytes = str.getBytes();
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.update(bytes);
			byte[] updateBytes = messageDigest.digest();
			int len = updateBytes.length;
			char[] myChar = new char[len * 2];
			int k = 0;
			for (int i = 0; i < len; i++) {
				byte byte0 = updateBytes[i];
				myChar[(k++)] = hexDigits[(byte0 >>> 4 & 0xF)];
				myChar[(k++)] = hexDigits[(byte0 & 0xF)];
			}

			return new String(myChar);
		} catch (Exception e) {
			throw new RuntimeException(str + " : md5失败", e);
		}
	}

	/**
	 * 根据字符串生成32位的sha串
	 * @param str 字符串 
	 * @return 生成后的sha串
	 * @throws Exception
	 */
	public static String sha(String str) throws Exception {
		char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			byte[] bt = str.getBytes();
			MessageDigest md = MessageDigest.getInstance("SHA-1"); 
			md.update(bt);
			byte[] updateBytes = md.digest();
			int len = updateBytes.length;
			char[] myChar = new char[32];
			int k = 0;
			for (int i = 0; i < len; i++) {
				byte byte0 = updateBytes[i];
				myChar[(k++)] = hexDigits[(byte0 >>> 4 & 0xF)];
			}
			for (int i = 0; i < (32-len); i++) {
				byte byte0 = updateBytes[i];
				myChar[(k++)] = hexDigits[(byte0 & 0xF)];
			}
			return new String(myChar);
		} catch (Exception e) {
			throw new RuntimeException(str + " : sha失败", e);
		}
	}
	
	/**
	 * 生成json字符串，适用于object有date或timestamp类型属性的时候
	 * @param obj 需要生成json的对象
	 * @param dateFormat 日期格式
	 * @param writeClassName 是否要写入类名
	 * @return json字符串
	 * yexuhui 2012-7-26 上午11:01:22
	 */
	public static String toJson(Object obj, String dateFormat,
			boolean writeClassName) {
		if(writeClassName)
			return JSON.toJSONStringWithDateFormat(obj, dateFormat, SerializerFeature.WriteClassName, 
				SerializerFeature.WriteMapNullValue);
		return JSON.toJSONStringWithDateFormat(obj, dateFormat, SerializerFeature.WriteMapNullValue);
	}	
	
	/**
	 * 导入properties文件
	 * @param fileName 文件名
	 * @return Properties对象
	 * @throws IOException
	 * yexuhui 2012-7-29 上午11:49:09
	 */
	public static Properties loadProperties(String fileName) throws IOException {
		InputStream is = null;
		try {
			is = Utils.class.getClassLoader().getResourceAsStream(fileName);
			Properties properties = new Properties();
			properties.load(is);
			return properties;
		} finally {
			if (is != null) is.close();
		}
	}	
	
	/**
	 * 缓存中的字符串转化为具体类型对象
	 * 目前该方法只在cache类中使用，该方法不是很精准，还需改进
	 * @param content 需要转化的字符串
	 * @param type 内容类型
	 * @return 具体类型对象
	 * @author yexuhui
	 * @date 2013-5-6 下午2:43:28
	 */
	@SuppressWarnings("unchecked")
	public static Object fromCacheStr(String content, Class<?> type) {
		Object value = null;
		
		if(type.equals(Integer.class)) 
			value = Integer.parseInt(content);
		else if(type.equals(Double.class)) 
			value = Double.parseDouble(content);
		else if(type.equals(Boolean.class)) 
			value = Boolean.parseBoolean(content);				
		else if(type.equals(Timestamp.class))
			value = DateUtils.str2Timestamp(content, DateUtils.NORMAL_FORMAT);
		else if(type.equals(Date.class))
			value = DateUtils.str2Date(content, DateUtils.NORMAL_FORMAT);	
		else if(type.equals(Map.class))
			value = (Map<String, Object>)JSON.parse(content);
		else
			value = content;		
		
		return value;
	}
	
	/**
	 * 将对象转化为缓存中的字符串
	 * @param value 对象实体
	 * @param type 对象类型
	 * @return 对象的字符串表现形式
	 * @author yexuhui
	 * @date 2013-5-6 下午3:08:20
	 */
	public static String toCacheStr(Object value, Class<?> type) {
		if(value == null)throw new RuntimeException("参数value为空转换为缓存中的字符串失败");
		
		String result = null;
		if (type.equals(Timestamp.class))
			result = DateUtils.timestamp2Str((Timestamp) value, DateUtils.NORMAL_FORMAT);
		else if (type.equals(Date.class))
			result = DateUtils.date2Str((Date) value, DateUtils.NORMAL_FORMAT);
		else if (type.equals(Map.class))
			result = JSON.toJSONString(value);
		else
			result = value.toString();
		return result;
	}

	public static boolean paramIsNotEmpty(Object object) {
		return (object != null && String.valueOf(object).length() != 0);
	}
	
}
